package dao;

import entity.IEntity;
import entity.Student;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;

/**
 *
 * @author Alexander
 */
public class StudentDAO implements IDAO {

    @Override
    public void persist(IEntity entity, EntityManager em) {
        em.persist(entity);
    }

    @Override
    public IEntity find(Object id, EntityManager em) {
        return (Student) em.find(Student.class, (String) id);
    }

    @Override
    public void update(IEntity entity, EntityManager em) {
        em.merge(entity);
    }

    public Student login(Student entity, EntityManager em) {
        Student alumno = null;
        Query q = em.createQuery("SELECT u FROM Student u "
                + "WHERE u.username LIKE :username "
                + "AND u.password LIKE :password").setParameter("username", entity.getUsername()).setParameter("password", entity.getPassword());

        try {
            alumno = (Student) q.getSingleResult();
        } catch (NonUniqueResultException e) {
            alumno = (Student) q.getResultList().get(0);
            //e.printStackTrace();
        } catch (NoResultException e){
            alumno = null;
        }
        return alumno;
    }

    @Override
    public void delete(Object id, EntityManager em) {
        Student alumno = em.getReference(Student.class, (String) id);
        em.remove(alumno);
    }

    /**
     * Busca un usuario basandose en la IP
     *
     * @param ip Ip del usuario
     * @param em Controlador de transacciones
     * @return El usuario buscado
     */
    public Student findByIP(Object ip, EntityManager em) {
        Student a;
        Query q = em.createQuery("SELECT u FROM Student u "
                + "WHERE u.activeUser = :usuario").setParameter("usuario", (String) ip);

        try {
            a = (Student) q.getSingleResult();
        } catch (NonUniqueResultException e) {
            a = (Student) q.getResultList().get(0);
            //e.printStackTrace();
        } catch (NoResultException e){
            a = null;
        }
        return a;
    }

    @Override
    public List<IEntity> getList(EntityManager em) {
        CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        cq.select(cq.from(Student.class));
        Query q = em.createQuery(cq);
        return q.getResultList();
    }
}
